<?php
class MY_Model extends CI_Model{
	
	var $TABLE = "";
	var $mainlistfields = array();
	var $ajaxmainlistfields = array();
	var $viewablefields = array();
	var $editablefields = array();
	var $searchfields = array();
	var $accessrights = array();
	var $dropdownfields = array();
	var $ckeditorfields = array();
	var $hasFile = false;
	
	//vieweditfields
	function __construct(){
		parent::__construct();
		$this->TABLE = get_called_class();

	}
	
	function loadfields(){
		$this->benchmark->mark('start_loadfields');
		$this->mainlistfields = array(
			DATA => $this->mainfields(
				    LABEL.",".FIELDS , 'mainlist' , 1 )
		);
		
		$this->ajaxmainlistfields = array(
			DATA => $this->mainfields(
				    LABEL.",".FIELDS , 'ajaxmainlist' , 1 )
		);
		
		$this->editablefields = array(
			DATA => $this->mainfields(
				    LABEL.",".FIELDS.",".TYPE.",".DEFAULT_VALUE.",".REQUIRED.",".UNIQUE,
				    'editable' , 1)
		);
		
		$this->viewablefields = array(
			DATA => $this->mainfields(
				    LABEL.",".FIELDS.",".TYPE.",".DEFAULT_VALUE, 'viewable' , 1)
		);
	
		$this->searchfields = array(
			DATA => $this->mainfields(
				    LABEL.",".FIELDS.",".TYPE.",".DEFAULT_VALUE , 'searchable' , 1 )
		);
		
		//$count = $this->mainfields("count(1)", TYPE , "file");		
		$this->benchmark->mark('start_loadfields');
	}
	
	function mainfields($select = "*" ,$field , $value){
		$this->db->select($select);
		$this->db->where($field , $value);
		$this->db->where("user_group", 1);
		$this->db->where("page", $this->table());
		$result = $this->db->get(FIELDS_TABLE);
		return $result->result_array();
	}
	
	function accessrights(){
		$this->db->where("usergroup_id", 1);
		$result = $this->db->get(ADMINPAGE_PERMISSION_TABLE);
		return $result->result_array();
	}
	
	function sessionuser(){
		$id = $this->session->userdata(LOGGED_IN_CLIENT_ID);
		$result = $this->find_by_id($id, "");
		
	}
	
	function max_id(){
		$this->db->select("max(id) as max_id");
		$result = $this->db->get($this->table());
		$max = $result->row_array();
		return $max['max_id'];
		//if(count($result) == 1)
		//return $result->result_array();
	}
	
	function find($id){
		$this->db->select("id");
		forEach($this->viewablefields[DATA] as $field)
			$this->db->select($field[FIELDS]);
		$this->db->where("id", $id);
		$this->db->where("valid", VALID);
		$result = $this->db->get($this->table());
		return $result->row_array();
	}
	
	function find_editable($id){
		$this->db->select("id");
		forEach($this->editablefields[DATA] as $field)
			$this->db->select($field[FIELDS]);
		$this->db->where("id", $id);
		$this->db->where("valid", VALID);
		$result = $this->db->get($this->table());
		return $result->row_array();
	}
	
	
	function insert($record = array()){
		if(count($record) > 0){
			$record['valid'] = VALID;
			$this->db->insert($this->table() , $record);
			$this->log("Insert New Record" , $this->last_inserted_id());
		}
	}
	
	function update($record = array()){
		if(count($record) > 0 && isset($record['id'])){
			$this->db->where("id" , $record['id']);
			$this->db->update($this->table() , $record);
			$this->log("Updated Record" , $record['id']);
		}
	}
	
	function delete($id){
		if( $id != null && $id != ""){
			$this->db->set("valid" , DELETED);
			$this->db->where("id" , $id);
			$this->db->update($this->table());
			$this->log("Deleted Record" , $id);
		}
	}
	
	function delete_permanently($id){
		if( $id != null && $id != ""){
			$this->db->where("id" , $id);
			//$this->db->delete($this->table());
			
		}
	}
	
	function mainListWithPaginationByField($field = "" , $value){
		$this->db->select("obj.$field as $field");
		$this->db->where("obj.$field", $value);
		return $this->mainListWithPagination();
	}
	
	function mainListWithPagination(){
		$this->db->select("obj.id as id");
		$this->db->where("obj.valid", VALID);
		$ctr = 0;
		forEach($this->mainlistfields[DATA] as $field){
			$pos = strrpos($field[FIELDS], "_id");
			if($pos > 0){
				$referencetable = str_replace("_id" , "" , $field[FIELDS]);
				$table_field = $field[FIELDS];
				$field = "name";
				if($referencetable == "group" || $referencetable == "usergroup"){
					$field = "name";
					$referencetable = "usergroup";
				}
				$this->db->join("$referencetable as $referencetable"."_"."$ctr" , "$referencetable"."_"."$ctr.id= obj.$table_field");
				
				if($referencetable == "users" ){
					$field = "firstname";
					$this->db->select("$field as $table_field");
				}else
					$this->db->select("$referencetable"."_".$ctr.".name as $table_field");
			}else{
				$this->db->select("obj.".$field[FIELDS]." as ".$field[FIELDS]);
			}
			$ctr++;
		}
		$this->db->order_by("obj.id" , "desc");
		$result = $this->db->get($this->table()." as obj");
		return $result->result_array();
	}
	
	function getDataForDropdown(){
		 
		$DROPDOWN = array();
		$dropdownFields = array(
			DATA => $this->mainfields(
				    LABEL.",".FIELDS.",".TYPE.",".DEFAULT_VALUE , 'inputtype' , 'dropdown' )
		);
		
		forEach($dropdownFields[DATA] as $dropDown){
				$referencetable = str_replace("_id" , "" , $dropDown[FIELDS]);
				$value = "name";
				if($referencetable == "group" || $referencetable == "usergroup"){
					$value = "name";
					$referencetable = "usergroup";
				}
				if($referencetable == "users" ){
					$value = "firstname";
				}
				$this->db->select("id");
				$this->db->where("valid", VALID);
				$this->db->select($value." as value");
				$result = $this->db->get($referencetable);
				$DROPDOWN[$dropDown[FIELDS]] = $result->result_array();
				
		} //coreassets/core/assets/ckeditor
		return $DROPDOWN;
	}
	
	function getCKEditorFields(){
		//$CKEDITOR = array();
		//echo "HEEEEEEEEEEEREEEEEEEEEEEEEEEEEE";
		$CKEDITOR = array(
			DATA => $this->mainfields(
				    LABEL.",".FIELDS.",".TYPE.",".DEFAULT_VALUE , 'inputtype' , 'ckeditor' )
		);
		//echo count($CKEDITOR[DATA]);
		
		
		return $CKEDITOR;
	}
	
	function last_inserted_id(){
		return $this->db->insert_id();
	}
	
	function check_duplicate($id , $field , $value){
		$this->db->select("count(1) as count");
		$this->db->where("id != $id");
		$this->db->where("valid", VALID);
		$this->db->where($field, $value);
		$result = $this->db->get($this->table());
		$record = $result->row_array();
		//has duplicate
		if($record['count'] != 0){
			return TRUE;
		}
		return FALSE;
	}
	
	function loadoptionsbyfield($field , $value){
		$this->db->select("name as label");
		$this->db->select("id as value");
		$this->db->where($field , $value);
		$this->db->where("valid", VALID);
		$result = $this->db->get($this->table());
		$record = $result->result_array();
		return $record;
	}
	
 	function table(){
	    /*********************************************
	     * Author Teody Ingeniero
	     * $this->table() is the tablename
	     * $this->setBaseValues($isInsert)--CreatedOn,UpdatedOn,createdBy,CreatedOn,valid
	     * *******************************************
	     */
    	
    	//model class name == current called class == needed table
    	
    	
    	if(preg_match('/_model$/', get_called_class())==1) {
    		$tablename = str_replace("_model", "", $this->TABLE);
    	} else {
    		show_error("Naming convention model class must be 'tablename_model'",500,"Error Model Name");
    	}
    	
    	return strtolower($tablename);
    }
    
    function log($message = "", $affectedId = ""){
	    	$record['valid'] = VALID;
	    	$record['message'] = $message;
	    	$record['affectedid'] = $affectedId;
	    	$record['affected_table'] = $this->table();
	    	$record['users_id'] = 1;
	    	$record['ip_address'] = $this->input->ip_address();
	    	$record['logged_date'] = date('Y-m-d H:i:s');
		$this->db->insert("log" , $record);
		
    }
	
}